// pages/exam/exam.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showUser: true,
    time: "",
    num: 0,
    startRestNum: 0,
    showAuth: false,
    showPage: false,
    showExamPage: false,
    showExam: false,
    examStatus: -1,
    authObj: {
      title: '登录提示',
      content: '您只有授权了，才可以参加考试哦！',
      confirmText: '知道了'
    },
    selectIndex: 0,
    totalNum: 10,
    optList: ["307", "317", "356", "352"],
    typeList: ["单选题", "多选题", "判断题", "问答题"],
    type: 4,
    questionList: [],
    timer: "",
    startTimer: "",
    startTime: "",
    endTime: "",
    showDanger: false,
    judgeScore: 0,
    multipleScore: 0,
    singleScore: 0,
    subjectScore: 0,
    startRestTime: "",
    examName: "",
    startTime: "",
    endTime: "",
    taskId: "",
    showMask: false,
    paperObj: {},
    userObj: {},
    showUserBox: false,
    companyList: [],
    companyIndex: 0,
    isWrite: false,
    userId: "",
    answerNum: 0,
    showFeedback: false,
    feedback: "",
    showSign: false,
    headImg: "",
    showTest: false,
    mobileNum: "",
    selectTime: 0,
    selectTimer: "",
    showCheck:false,
    durations:0,
    isContinue: false //是否切出重新答题
  },
  /**
   * 生命周期函数--监听页面加载
   */
  //打开签到弹框
  openSign() {
    this.setData({
      showUserBox: true
    })
  },
  //签到
  sign() {
    if (!this.data.isWrite) return
    app.api.updateUserInfo(this.data.userId, this.data.userObj)
    wx.showToast({
      title: '签到成功！',
      icon: 'none'
    })
    this.setData({
      showUserBox: false
    })
  },
  // 打开用户反馈弹框
  openFeedBox() {
    this.setData({
      showFeedback: true
    })
  },
  closeFeedBox() {
    this.setData({
      showFeedback: false
    })
  },
  //选择手机号码最后一位
  selectMobile(e) {
    let index = e.currentTarget.dataset.index
    let _this = this
    clearInterval(this.data.selectTimer)
    this.setData({
      mobileNum: index,
    })
    setTimeout(function() {
      _this.setData({
        showTest: false
      })
    }, 200)
  },
  bindFeed(e) {
    this.setData({
      feedback: e.detail.value
    })
  },
  submitFeed() {
    if (!this.data.feedback) return wx.showToast({
      title: '请填写您要反馈的内容',
      icon: "none"
    })
    app.api.submitPaper(this.data.paperId, {
        feedback: this.data.feedback
      })
      .then(res => {
        wx.showToast({
          title: '我们已经收到您的反馈，谢谢！',
          icon: "none"
        })
        this.setData({
          showFeedback: false
        })
      })
  },
  onLoad: function(options) {
    this.setData({
      taskId: decodeURIComponent(options.scene)
    })
    wx.showLoading()
    this.login()
    this.getCompanyList()
  },
  //获取城市列表
  getCompanyList() {
    app.api.getCompanyList()
      .then(res => {
        this.setData({
          companyList: res.content
        })
      })
  },
  companyChange(e) {
    let companyIndex = e.detail.value
    this.setData({
      companyIndex: e.detail.value,
      ["userObj.company"]: this.data.companyList[companyIndex].id
    })
  },
  // 用户基本信息填写
  changeInfo(e) {
    let name = e.currentTarget.dataset.key
    let val = e.detail.value
    this.setData({
      ["userObj." + name]: val
    })
    this.setData({
      isWrite: this.checkUserInfo()
    })
  },
  checkUserInfo() {
    return Boolean(this.data.userObj.name && this.data.userObj.project)
  },
  goStudy() {
    wx.switchTab({
      url: '../home/home'
    })
  },
  goHome() {
    wx.switchTab({
      url: '../home/home'
    })
  },
  //用户登陆获取登陆态
  login() {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        var _this = this
        // return
        if (res.code) {
          wx: wx.request({
            url: 'https://t.weijiayingxiao.com/login',
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded",
              'cookie': wx.getStorageSync('session')
            },
            data: {
              code: res.code
            },
            success: function(res) {
              _this.saveSession(res)
            }
          })
        }
      }
    })
  },
  // 保存用户session到本地
  saveSession: function(res) {
    // console.log(res)
    var _this = this
    var sessionId = (res.header['set-cookie'] || res.header['Set-Cookie']) && (res.header['set-cookie'] || res.header['Set-Cookie']).split(';')[0]
    if (sessionId) {
      wx.setStorage({
        key: 'session',
        data: sessionId,
        success: function() {
          _this.saveInfo()
        }
      })
    } else {
      _this.saveInfo()
    }
  },
  //打开选项板
  openMask() {
    this.setData({
      showMask: !this.data.showMask
    })
  },
  //关闭选项版
  closeMask() {
    this.setData({
      showMask: false
    })
  },
  currentChange(e) {
    this.setData({
      selectIndex: e.detail.current
    })
  },
  preShow() {
    if (this.data.selectIndex == 0) return
    this.setData({
      selectIndex: this.data.selectIndex - 1,
      showMask: false
    })
  },
  nextShow() {
    if (this.data.selectIndex + 1 == this.data.totalNum) return
    this.setData({
      selectIndex: this.data.selectIndex + 1,
      showMask: false
    })
  },
  changeIndex(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      selectIndex: index,
      showMask: false
    })
  },
  currentChange(e) {
    this.setData({
      selectIndex: e.detail.current
    })
  },
  bindGetUserInfo: function(e) {
    this.setData({
      showAuth: false
    })
    this.saveInfo()
  },
  saveInfo: function() {
    var _this = this
    wx.getUserInfo({
      success: function(data) {
        wx.hideLoading()
        // console.log(data)
        _this.setData({
          showPage: true,
          showExamPage: true
        })
        var dataObj = {
          encryptedData: data.encryptedData,
          iv: data.iv
        }
        app.api.saveUserInfo(dataObj)
          .then(res => {
            app.globalData.nickname = res.name || res.nickname
            app.globalData.icon = res.icon
            app.globalData.userId = res.id
            let company = res.company
            let change = false
            if (company) {
              _this.data.companyList.forEach((item, index) => {
                if (company == item.id) {
                  change = true
                  _this.setData({
                    companyIndex: index
                  })
                }
              })
            } else {
              company = _this.data.companyList[0].id
            }
            let userObj = {
              name: res.name,
              company: company,
              project: res.project
            }
            _this.setData({
              userObj: userObj,
              userId: res.id,
              headImg: res.icon
            })
            _this.setData({
              isWrite: _this.checkUserInfo()
            })
            _this.getPaperId()
            // if (!userObj.name)
          })
      },
      fail: function(data) {
        wx.hideLoading()
        // wx.showToast({
        //   title: "只有授权之后才能开始考试哦！",
        //   icon: 'none'
        // })
        _this.setData({
          showPage: true,
          showAuth: true
        })
      }
    })
  },
  getPaperId() {
    app.api.getPaperId(this.data.taskId, this.data.userId)
      .then(res => {
        let startTime = this.strToDate(res.task.begin).getTime()
        let endTime = this.strToDate(res.task.end).getTime()
        let nowTime = Date.now()
        // let submit = res.submit
        wx.getStorageSync('startTime') == "" ? wx.setStorageSync('startTime', nowTime) : null
        this.setData({
          paperId: res.id,
          examName: res.task.title,
          startTime: res.task.begin,
          endTime: res.task.end,
          paperObj: res,
          durations: res.task.duration*60
        })
        this.setData(res.setting.scoreSetting)
        wx.setNavigationBarTitle({
          title: res.task.title
        })
        if (nowTime < startTime) {
          let startTimer = setInterval(() => {
            this.setStartTime()
          }, 1000)
          this.setData({
            showUserBox: !Boolean(this.data.userObj.name)
          })
          this.setData({
            startRestNum: Math.floor((startTime - nowTime) / 1000),
            showExam: false,
            examStatus: "noBegin",
            startTimer: startTimer,
          })
          this.setStartTime()

        } else if (nowTime > endTime) {
          this.setData({
            showExam: false,
            examStatus: "end"
          })
        } else {
          let num = this.data.num == 0 ? this.data.durations : this.data.num;
          console.log('num', num);
          this.setData({
           // num: Math.floor((endTime - nowTime) / 1000),
            num: num,
            examStatus: res.submit ? "end" : "going",
            showExam: !res.submit,
            showUserBox: !res.submit
          })
          //this.setEndTime()
          wx.setStorageSync('totalTime', this.data.durations)
          this.getPaperInfo()
        }
      })

  },
  startExam() {
    if (!this.data.isWrite) return

    // let num = this.data.isContinue ? this.data.num : this.data.durations;
    // let gap = Math.floor((nowTime - wx.getStorageSync('startTime')) / 1000);
    // console.log(wx.getStorageSync('time'));
    // 
    // let nums = wx.getStorageSync('time') == '' ? this.data.durations : (wx.getStorageSync('time') - gap);
    // console.log(nums);
    // let num = this.data.num;
    // 新增验证
    let user = this.data.userObj;
    let task = parseInt(this.data.taskId);
    app.api.getPaperByUser(task,this.data.userId ,user).then(res => {
      if (res != 0) {
        wx.showToast({
          title: '您已参加过本场考试！',
          icon: 'none'
        })
        return;
      }
      wx.getStorageSync('startExamTime') ? null : wx.setStorageSync('startExamTime', new Date().getTime());
      let timer = setInterval(() => {
        this.setEndTime()
      }, 1000)
      let endTime = this.strToDate(this.data.paperObj.task.end).getTime()
      let nowTime = Date.now(); 
    let currentPaper = this.data.isContinue ? this.data.selectIndex : (this.data.paperObj.finish ? this.data.paperObj.finish - 1 : 0) 
    this.setData({
      selectIndex: currentPaper,
      timer: timer,
      // num: Math.floor((endTime - nowTime) / 1000),
      // num: nums,  
      examStatus: "going",
      showExam: true,
      showUserBox: false 
    })

    // this.setEndTime()
    app.api.updateUserInfo(this.data.userId, this.data.userObj);
    this.getPaperInfo()
    })
  },
  // 考试开始倒计时
  setStartTime() {
    let diff = this.data.startRestNum - 1
    if (diff <= 0) {
      clearInterval(this.data.startTimer)
      // return this.startExam()
      this.setData({
        showExam: true,
        showUserBox: !this.data.isContinue
      })
    }
    let hour = this.checkTime(parseInt(diff / 3600 % 60, 10))
    let minute = this.checkTime(parseInt(diff / 60 % 60, 10))
    let second = this.checkTime(parseInt(diff % 60, 10))
    this.setData({
      startRestNum: diff,
      startRestTime: hour + ":" + minute + ":" + second
    })
  },
  //考试结束倒计时
  setEndTime() {
    let diff = this.data.num - 1;
    wx.setStorageSync('time', diff)
    if (diff <= 0) {
      console.log('diff',diff);
      clearInterval(this.data.timer)
      app.api.submitPaper(this.data.paperId, {
          submit: true
        })
        .then(res => {
          this.setData({
            showExam: false,
            examStatus: "end",
            paperObj: res,
            num: diff
          })
          //清除缓存
          wx.clearStorage();
        })
      return
    }
    let hour = this.checkTime(parseInt(diff / 3600 % 60,10 ))
    let minute = this.checkTime(parseInt(diff / 60 % 60, 10))
    let second = this.checkTime(parseInt(diff % 60, 10))
    this.setData({
      num: diff,
      time: hour + ":" + minute + ":" + second
    });
  },
  checkTime(i) {
    return i < 10 ? "0" + i.toString() : i.toString();
  },
  strToDate(dateStr) {
    dateStr = dateStr.replace(/\-/g, '/')
    return new Date(dateStr)
  },
  getPaperInfo() {
    let obj = {
      page: 0,
      size: 200
    }
    app.api.getPaperInfo(this.data.paperId, obj)
      .then(res => {
        let questionList = res.content
        let arr = [];
        debugger
        let answers = wx.getStorageSync('answer');
        questionList.forEach(item => {
          let obj = {};
          if(answers){
            let temp = answers.find(answer => answer.questionId == item.id );
            item.answer = temp ? temp.answer :item.answer
          }
          let titleObj = JSON.parse(item.question.body);

          obj.typeText = this.formatType(item.question.type)
          obj.title = titleObj.title
          obj.imgSrc = titleObj.imgSrc
          obj.audioSrc = titleObj.audioSrc
          obj.videoSrc = titleObj.videoSrc
          obj.type = item.question.type
          obj.trueVal = item.question.answer
          obj.answerId = item.id
          obj.answer = item.answer || ""
          obj.videoSrc ? obj.showMask = true : ""
          obj.paper = item.paper;
          obj.questionId = item.id;
          obj.score = item.score;
          obj.user = item.user;
          if (item.question.options.length) {
            let arr1 = []
            item.question.options.forEach((item1, index) => {
              arr1.push({
                text: this.formatOpt(index + 1) + item1,
                checked: obj.answer.indexOf(String(index)) != -1
              })
            })
            obj.options = arr1
          }
          arr.push(obj)
        })
        this.setData({
          totalNum: arr.length,
          questionList: arr
        })
        let answerNum = 0
        arr.forEach(item => {
          if (item.answer) answerNum++
        })
        this.setData({
          answerNum: answerNum
        })
        this.initVideo()
      })
  },
  initVideo() {
    let questionList = this.data.questionList
    questionList.forEach((item, index) => {
      if (item.videoSrc) this['videoContext' + index] = wx.createVideoContext('video' + index)
    })
  },
  bindPlay(e) {
    let index = e.currentTarget.dataset.index
    // console.log(this)
    this.setData({
      ['questionList[' + index + '].showMask']: false
    })
    this['videoContext' + index].requestFullScreen()
    this['videoContext' + index].play()
  },
  bindfullscreenchange(e) {
    console.log(e)
    let index = e.currentTarget.dataset.index
    if (!e.detail.fullScreen) {
      this.setData({
        ['questionList[' + index + '].showMask']: true
      })
    }
  },
  formatOpt(index) {
    switch (index) {
      case 1:
        return "A "
        break;
      case 2:
        return "B "
        break;
      case 3:
        return "C "
        break;
      case 4:
        return "D "
        break;
      case 5:
        return "E "
        break;
      case 6:
        return "F "
        break;
      case 7:
        return "G "
        break;
      case 8:
        return "H "
        break;
      case 9:
        return "I "
        break;
      case 10:
        return "J "
        break;
      case 11:
        return "K "
        break;
      case 12:
        return "L "
        break;
      case 13:
        return "M "
        break;
      case 14:
        return "N "
        break;
      case 15:
        return "O "
        break;
    }
  },
  formatType(type) {
    switch (type) {
      case 1:
        return "单选题"
        break;
      case 2:
        return "多选题"
        break;
      case 3:
        return "判断题"
        break;
    }
  },
  //
  // 下一步的时候提交答案分数到数据库
  next() {
    let index = this.data.selectIndex
    let currentObj = this.data.questionList[index]
    console.log(currentObj);
    if (!currentObj.answer) return wx.showToast({
      title: '作答之后方可提交！',
      icon: 'none',
      duration: 2000
    })
    let score = 0
    if (currentObj.answer === currentObj.trueVal) {
      score = this.formatScore(currentObj.type);
    }   
    let obj = {
      score: score,
      answer: currentObj.answer
    }
    this.updateAnswer(currentObj.answerId, obj)
    let nextIndex = index + 1
    let nextText = this.data.questionList[nextIndex].typeText
    this.setData({
      typeText: nextText,
      selectIndex: nextIndex
    })
  },
  formatScore(type) {
    switch (type) {
      case 1:
        return this.data.singleScore
        break;
      case 2:
        return this.data.multipleScore
        break;
      case 3:
        return this.data.judgeScore
        break;
      case 4:
        return 0
        break;
    }
  },
  //用户选择答案更新
  updateAnswer() {
    let index = this.data.selectIndex
    let currentObj = this.data.questionList[index]
    let answerId = currentObj.answerId
    let score = 0
    let answerNum = 0
    this.data.questionList.forEach(item => {
      if (item.answer) answerNum++
    })
    this.setData({
      answerNum: answerNum
    })
    if (currentObj.answer != currentObj.trueVal) {
      score = 0;
    } else {
      score = this.formatScore(currentObj.type);
    }
    let obj = {
      score: score,
      answer: currentObj.answer
    }
    if (answerNum == Math.floor(this.data.questionList.length / 2) && this.data.mobileNum === "") {
      if(this.data.paperObj.task.authentication==true){
        let _this = this
        let selectTimer = setInterval(function () {
          _this.setData({
            selectTime: _this.data.selectTime + 1
          })
        }, 1000)
        this.setData({
          selectTimer: selectTimer,
          showTest: true
        });
      }
    }
    app.api.updateAnswer(answerId, obj, app.globalData.userId)
  },
  //判断题选择
  checkOpt(e) {
    // console.log(e)
    let val = e.currentTarget.dataset.val
    this.setData({
      ["questionList[" + this.data.selectIndex + "].answer"]: String(val)
    })
    this.updateAnswer()
  },
  // 单选题选择
  radioOpt(e) {
    // console.log(e)
    let index = e.currentTarget.dataset.index
    this.setData({
      ["questionList[" + this.data.selectIndex + "].answer"]: String(index)
    })
    this.updateAnswer()
  },
  //多选题选择
  selectOpt(e) {
    // console.log(e)
    let index = e.currentTarget.dataset.index
    let val = !this.data.questionList[this.data.selectIndex].options[index].checked
    this.setData({
      ["questionList[" + this.data.selectIndex + "].options[" + index + "].checked"]: val
    })
    let arr = []
    this.data.questionList[this.data.selectIndex].options.forEach((item, index) => {
      if (item.checked) {
        arr.push(index)
      }
    })
    this.setData({
      ["questionList[" + this.data.selectIndex + "].answer"]: arr.length ? "[" + arr.join(",") + "]" : ""
    })
    this.updateAnswer()
  },
  submit() {
    let _this = this
    debugger
    wx.showModal({
      title: '提示',
      content: '您确定要交卷吗？',
      success: function(res) {
        if (res.confirm) {
          app.api.submitPaper(_this.data.paperId, {
              submit: true,
              authenticationDelay: _this.data.selectTime,
              authenticationValue: _this.data.mobileNum
            })
            .then(res => {
              _this.setData({
                showExam: false,
                examStatus: "end",
                paperObj: res
              })
            })
            wx.clearStorage();
            //批量提交
          // let parames = [];
          // _this.data.questionList && _this.data.questionList.forEach(item => {
          //   parames.push({
          //     answer: item.answer,
          //     answerId: item.answerId,
          //     title: item.title,
          //     type: item.type,
          //     score: item.score,
          //     user: item.user,
          //     paper: item.paper,
          //     questionId: item.questionId,
          //     taskId: _this.data.taskId
          //   })
          // })
          // app.api.submitPaperByAll(parames)
          //   .then(res => {
          //     _this.setData({
          //       showExam: false,
          //       examStatus: "end",
          //       paperObj: res
          //     })
          //   })
          //   wx.clearStorage();
        } else if (res.cancel) {
          // _this.setData()
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    console.log('ready--->')
    clearInterval(this.data.timer);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    clearInterval(this.data.timer);
    let startTime = this.strToDate(this.data.startTime).getTime()
    let endTime = this.strToDate(this.data.endTime).getTime()
    let nowTime = Date.now()
    let startRestNum = Math.floor((startTime - nowTime) / 1000)
    // 直接切入后台不做缓存时间差值判断，定时器仍在运行
    console.log(this.data.isContinue)
    let startExamTime = wx.getStorageSync('startExamTime') || 0;
    let totalTime = wx.getStorageSync('totalTime') || 0;
    let examedTime =  Math.floor((nowTime - startExamTime)/1000);
    let num = (totalTime - examedTime) < 0 ? 0 : (totalTime - examedTime);

    // if(this.data.isContinue) {
    //   console.log('time',wx.getStorageSync('time'))
    //   num = wx.getStorageSync('time')
    // }else {
    //   // let gap = wx.getStorageSync('time') == '' ? (nowTime / 1000) : Math.floor((nowTime - wx.getStorageSync('startTime')) / 1000);
    //   // // num = wx.getStorageSync('time') == '' ? this.data.durations : (wx.getStorageSync('time') - gap);
    //   // num = wx.getStorageSync('time') == '' ? this.data.durations : (wx.getStorageSync('totalTime') - gap);
    //   // console.log('time',wx.getStorageSync('time'));
    //   // console.log('totalTime',wx.getStorageSync('totalTime'));
    //   // console.log('num',num)
    //   console.log(nowTime);
    //   let startExamTime = wx.getStorageSync('startExamTime') || 0;
    //   let totalTime = wx.getStorageSync('totalTime') || 0;
    //   let examedTime =  Math.floor((nowTime - startExamTime)/1000);
    //   num = (totalTime - examedTime) < 0 ? 0 : (totalTime - examedTime);
    //   console.log('time--->',num)

    // }
    // console.log(wx.getStorageSync('time'));
    // console.log(wx.getStorageSync('totalTime'));
    // console.log(num)
    this.setData({
      startRestNum: startRestNum,
      num: num
    })
    this.data.isContinue ? clearInterval(this.data.timer) :  null;
    this.setStartTime()
    this.data.isContinue ? this.startExam(): null;
    // this.setEndTime()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      isContinue: true
    })
    wx.setStorageSync('time', this.data.num)
    wx.setStorageSync('answer',this.data.questionList);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})